package com.kexin.coupon.api;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.kexin.common.config.WebAppConfigurer;
import com.kexin.common.user.service.IConfigDataService;
import com.kexin.common.utils.ApplicationContextUtil;
import com.kexin.common.utils.HttpURLRequestUtils;
import com.kexin.coupon.config.CouponConfig;


/**
 * 卡券申领平台接口
 * @author ao
 */
public class CouponApi {

	static Logger log = LoggerFactory.getLogger(CouponApi.class);

	private final static String TOKEN_NAME = "couponAuthorizationToken";

	/**
	 * 公共请求参数
	 * @return
	 */
	private static Map<String, Object> getHeader(String channelType) {
		Date nowDate = new Date();
		Map<String, Object> header = new HashMap<String, Object>();
		header.put("appId", CouponConfig.getAppId());
		header.put("channelType", channelType);
		header.put("outReqDate", DateFormatUtils.format(nowDate, "yyyy-MM-dd"));
		header.put("outReqTime", DateFormatUtils.format(nowDate, "HH:mm:ss"));
		header.put("version", CouponConfig.getVersion());
		return header;
	}

	/**
	 * 获取token
	 * @return
	 */
	public static String getAuthorization(boolean isCache) {
		log.info("调用卡券平台的获取token接口");
		IConfigDataService configDataService = ApplicationContextUtil.getConfigDataService();
		String authorizationToken = null;
		if (isCache) {
			authorizationToken = configDataService.getValue(TOKEN_NAME);
		}
		String authorization = null;
		if (StringUtils.isNotEmpty(authorizationToken)) {
			try {
				JSONObject tokenData = JSONObject.parseObject(authorizationToken);
				String time = tokenData.getString("time");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = sdf.parse(time);
				
				Calendar calendar = Calendar.getInstance();
				calendar.add(Calendar.HOUR, -11);
				if (calendar.getTime().before(date)) {
					authorization = tokenData.getString("token");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (StringUtils.isEmpty(authorization)) {
			Map<String, String> param = new HashMap<String, String>();
			param.put("clientId", CouponConfig.getClientId());
			param.put("clientSecret", CouponConfig.getClientSecret());
			param.put("grantType", CouponConfig.getGrantType());
			param.put("appId", CouponConfig.getAppId());
			String result = HttpURLRequestUtils.httpURLRequest(
					CouponConfig.getBaseUrl()+CouponConfig.getGetAuthorizationUrl(), 
					null, param, "utf-8");
			JSONObject response = JSONObject.parseObject(result);
			if ("0".equals(response.getString("code"))) {
				JSONObject data = response.getJSONObject("data");
				authorization = data.getString("access_token");
				JSONObject tokenData = new JSONObject();
				tokenData.put("token", authorization);
				tokenData.put("time", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
				configDataService.saveData(TOKEN_NAME, tokenData.toJSONString());
			}
		}
		return authorization;
	}

	/**
	 * 查询卡券列表
	 * @param channelType 卡券渠道类型
	 * @return
	 */
	public static Map<String, Object> queryCouponList(String channelType) {
		log.info("调用卡券平台的查询卡券列表接口");
		Map<String, Object> body = new HashMap<String, Object>();
		JSONObject param = new JSONObject();
		param.put("header", getHeader(channelType));
		param.put("body", body);
		Map<String, String> headrs = new HashMap<String, String>();
		headrs.put("Authorization", "Bearer "+getAuthorization(false));
		String result = HttpURLRequestUtils.httpURLRequest(
				CouponConfig.getBaseUrl()+CouponConfig.getQueryCouponListUrl(), 
				headrs, param.toJSONString(), "utf-8");
		
		return JSONObject.parseObject(result);
	}

	/**
	 * 卡券申领，用于外部系统向卡券平台申领卡券
	 * @param channelType 卡券渠道类型
	 * @param outOrderNo 申领流水号 外部系統保持唯一
	 * @param applyCount 申领数量
	 * @param couponCode 卡券编码
	 * @param applyUserType 申领用户类型 1个人  2机构
	 * @param mobile 用户手机号，分配给用户时必填，申领用户类型为1时,且渠道方为中石油时必填
	 * @return
	 */
	public static Map<String, Object> busiApply(String channelType, String outOrderNo, 
			int applyCount, String couponCode, String applyUserType, String mobile) {
		log.info("调用卡券平台的申领接口");
		Map<String, Object> body = new HashMap<String, Object>();
		body.put("outOrderNo", outOrderNo);
		body.put("applyCount", ""+applyCount);
		body.put("couponCode", couponCode);
		body.put("applyUserType", applyUserType);
		body.put("mobile", mobile);
		//body.put("outMerchantNo", outMerchantNo);
		//body.put("openId", openId);
		//body.put("openIdSource", openIdSource);
		//body.put("cardNo", cardNo);
		body.put("notifyUsedResult", WebAppConfigurer.getBaseUrl()+CouponConfig.getBusiUsedResultUrl());
		
		JSONObject param = new JSONObject();
		param.put("header", getHeader(channelType));
		param.put("body", body);
		Map<String, String> headrs = new HashMap<String, String>();
		headrs.put("Authorization", "Bearer "+getAuthorization(false));
		String result = HttpURLRequestUtils.httpURLRequest(
				CouponConfig.getBaseUrl()+CouponConfig.getBusiApply(), 
				headrs, param.toJSONString(), "utf-8");
		
		return JSONObject.parseObject(result);
	}

	/**
	 * 卡券退货
	 * @param channelType 卡券渠道类型
	 * @param outOrderNo 退货流水号 外部系統保持唯一
	 * @param origOutOrderNo 原申领订单号 外部系統保持唯一
	 * @param couponCode 卡券编码
	 * @param couponNo 卡券编号
	 * @return
	 */
	public static Map<String, Object> busiRefund(String channelType, String outOrderNo, 
			String origOutOrderNo, String couponCode, String couponNo) {
		log.info("调用卡券平台的卡券退货接口");
		Map<String, Object> body = new HashMap<String, Object>();
		body.put("outOrderNo", outOrderNo);
		body.put("origOutOrderNo", origOutOrderNo);
		body.put("couponCode", couponCode);
		body.put("couponNo", couponNo);
		
		JSONObject param = new JSONObject();
		param.put("header", getHeader(channelType));
		param.put("body", body);
		Map<String, String> headrs = new HashMap<String, String>();
		headrs.put("Authorization", "Bearer "+getAuthorization(false));
		String result = HttpURLRequestUtils.httpURLRequest(
				CouponConfig.getBaseUrl()+CouponConfig.getBusiRefund(), 
				headrs, param.toJSONString(), "utf-8");
		
		return JSONObject.parseObject(result);
	}}
